package com.szholly.data.general.interceptor.defulat;

import java.util.List;

import org.apache.log4j.Logger;

import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.*;
import com.szholly.data.general.interceptor.*;
import com.szholly.data.jdbc.DatabaseWorkspaceBase;

/**
 * 版本检查
 * 
 */
public class VersionCheckInterceptor extends DbEditInterceptorClass {

	private static Logger logger = Logger.getLogger(VersionCheckInterceptor.class);
	
	public VersionCheckInterceptor() {
		super.setIndex(-90);
	}
	
	@Override
	public void BeforeDbEditOption(ITable table, Object editEntitys,
			DbEditType editType) {
		if (editType == DbEditType.Update) {
			// 没有版本字段，不处理版本检查
			String versionField = table.getVersionFieldName();
			if (StringUtils.IsNullOrSpace(versionField)) {
				return;
			}

			if (editEntitys instanceof RowBase) {
				versionChekc(table, (RowBase) editEntitys);
			} else {
				logger.warn("【UniqueCheckInterceptor】  非单一RowBase保存，不处理数据版本检查！");
			}
		}
	}

	@Override
	public void DbEditOptionException(ITable table, Object editEntitys,
			DbEditType editType, Exception ex) {
	}

	@Override
	public void AfterDbEditOption(ITable table, Object editEntitys,
			DbEditType editType) {
	}

	@Override
	public String getInterceptorName() {
		return "版本检查";
	}

	/**
	 * 版本号检查
	 * 
	 * @param table
	 * @param entity
	 */
	protected final void versionChekc(ITable table, RowBase entity) {

		String selfWhere = DatabaseWorkspaceBase.getUpdateWhere(table);
		List<GlobalParameter> selfWherePara = DatabaseWorkspaceBase
				.getUpdateWhereParameter(table, entity);

		String versionField = table.getVersionFieldName();

		String sqlString = "select " + versionField + " from "
				+ table.getTableName();
		sqlString += " where " + selfWhere;

		Object ct = table.getWorkspace()
				.getExecuteScalar(
						sqlString,
						selfWherePara.toArray(new GlobalParameter[selfWherePara
								.size()]));
		if (ct != null) {
			int version = Integer.parseInt(ct.toString());
			int cVersion = (int) entity.getValue(GlobalDataType.Int32,
					versionField);
			cVersion++;
			if (cVersion <= version) {
				throw new VersionCheckException("当前数据已经被更新！");
			}else{
				entity.setValue(versionField, cVersion);
			}
		}
	}
}
